package com.example.content.viewmodule.login

import com.example.content.App
import com.example.content.repository.bean.UserToken
import com.example.core.network.MoshiHelper
import com.example.core.store.clearSpValue
import com.example.core.store.getSpValue
import com.example.core.store.putSpValue

/**
 * Created by zhudongao
 * Desc
 * Date 2020/11/2
 */
object TokenStore {
    private const val SP_TOKEN_INFO = "sp_token_info"
    private const val KEY_TOKEN_INFO = "key_token_info"
    private const val KEY_ACCESS_TOKEN = "key_access_token"
    private const val KEY_USER_ID = "key_user_id"
    private const val KEY_SEXY_TYPE = "key_sexy_type"

    var token = ""
        get() {
            if (field.isBlank()) {
                field = getSpValue(SP_TOKEN_INFO, App.appContext, KEY_ACCESS_TOKEN, "")
            }
            return field
        }

    var userId: Int = -1
        get() {
            if (field == -1) {
                field = getSpValue(SP_TOKEN_INFO, App.appContext, KEY_USER_ID, -1)
            }
            return field
        }

    var sexyType = -1
        get() {
            if (field == -1) {
                field = getSpValue(SP_TOKEN_INFO, App.appContext, KEY_SEXY_TYPE, 1)
            }
            return field
        }

    fun getUserInfo(): UserToken? {
        val userToken = getSpValue(SP_TOKEN_INFO, App.appContext, KEY_TOKEN_INFO, "")
        return MoshiHelper.fromJson<UserToken>(userToken)
    }

    fun setUserToken(userToken: UserToken) {
        token = userToken.access_token
        userId = userToken.user_id
        putSpValue(SP_TOKEN_INFO, App.appContext, KEY_TOKEN_INFO, MoshiHelper.toJson(userToken))
        putSpValue(SP_TOKEN_INFO, App.appContext, KEY_ACCESS_TOKEN, token)
        putSpValue(SP_TOKEN_INFO, App.appContext, KEY_USER_ID, userId)
    }

    fun setSexType(sexType: Int) {
        sexyType = sexType
        putSpValue(SP_TOKEN_INFO, App.appContext, KEY_SEXY_TYPE, sexType)
    }

    fun logout() {
        clearSpValue(SP_TOKEN_INFO, App.appContext)
        token = ""
        userId = -1
    }
}